package com.matrix.framework.core.component;

import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;

/**
 * Token续期工具类
 * 
 * Copyright © 海平面工作室 版权所有
 *
 * @Author: Leo
 * @Create: 2025/06/21 12:35
 * @Since 1.2
 */
public class TokenRefreshUtil {
    
    // 响应头键名常量
    public static final String HEADER_NEW_TOKEN = "X-New-Token";
    public static final String HEADER_TOKEN_REFRESHED = "X-Token-Refreshed";
    public static final String HEADER_TOKEN_REMAINING_TIME = "X-Token-Remaining-Time";
    
    /**
     * 在响应头中设置新的token
     * @param response 响应对象
     * @param newToken 新的token
     */
    public static void setNewTokenInResponse(ServerHttpResponse response, String newToken) {
        response.getHeaders().add(HEADER_NEW_TOKEN, newToken);
        response.getHeaders().add(HEADER_TOKEN_REFRESHED, "true");
    }
    
    /**
     * 在响应头中设置token剩余时间
     * @param response 响应对象
     * @param remainingTimeMs 剩余时间（毫秒）
     */
    public static void setTokenRemainingTime(ServerHttpResponse response, long remainingTimeMs) {
        response.getHeaders().add(HEADER_TOKEN_REMAINING_TIME, String.valueOf(remainingTimeMs));
    }
    
    /**
     * 从请求中提取token
     * @param exchange 请求交换对象
     * @return token字符串，如果没有则返回null
     */
    public static String extractToken(ServerWebExchange exchange) {
        String authHeader = exchange.getRequest().getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            return authHeader.substring(7);
        }
        return null;
    }
    
    /**
     * 检查并处理token续期
     * @param exchange 请求交换对象
     * @param jwt JWT工具类实例
     * @return 是否成功验证token
     */
    public static boolean checkAndRefreshToken(ServerWebExchange exchange, Jwt jwt) {
        String token = extractToken(exchange);
        if (token == null) {
            return false;
        }
        
        try {
            String username = jwt.extractUsername(token);
            if (username == null) {
                return false;
            }
            
            Jwt.TokenValidationResult validationResult = jwt.validateTokenWithResult(token, username);
            
            if (validationResult.isValid()) {
                // 设置剩余时间
                long remainingTime = jwt.getRemainingTime(token);
                setTokenRemainingTime(exchange.getResponse(), remainingTime);
                
                // 如果需要续期
                if (validationResult.needsRefresh() && validationResult.getNewToken() != null) {
                    setNewTokenInResponse(exchange.getResponse(), validationResult.getNewToken());
                }
                return true;
            }
        } catch (Exception e) {
            return false;
        }
        
        return false;
    }
    
    /**
     * 获取token剩余时间的可读格式
     * @param remainingTimeMs 剩余时间（毫秒）
     * @return 可读的时间格式
     */
    public static String getReadableRemainingTime(long remainingTimeMs) {
        if (remainingTimeMs <= 0) {
            return "已过期";
        }
        
        long minutes = remainingTimeMs / (1000 * 60);
        long seconds = (remainingTimeMs % (1000 * 60)) / 1000;
        
        if (minutes > 0) {
            return minutes + "分" + seconds + "秒";
        } else {
            return seconds + "秒";
        }
    }
} 